<template lang="pug">
.cp-order-edit
  el-dialog(:title="title", :visible="visible", width="80%", @close="close", :close-on-click-modal="false")
    el-form.ot-form(:inline="true", label-width="72px")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="采购单号")
            el-input(:disabled="true", v-model="formData.order", placeholder="系统自动生成")
        el-col(:span="12")
          el-form-item.is-required(label="申请人")
            el-select(:disabled="pushPlan", v-model="formData.applicant", placeholder="请选择")
              el-option(v-for="item in empSelect", :key="item.value", :label="item.name", :value="item.value")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="需求部门")
            el-select(:disabled="pushPlan", v-model="formData.depart", placeholder="请选择")
              el-option(v-for="item in oneDeptSelect", :key="item.value", :label="item.name", :value="item.value")
        el-col(:span="12")
          el-form-item.is-required(label="供应商")
            el-select(:disabled="pushPlan", v-model="formData.supply", placeholder="请选择", @change="changeSupply")
              el-option(v-for="item in supplySelect", :key="item.value", :label="item.name", :value="item.value")
      el-row(:gutter="36")
        el-col(:span="8")
          el-form-item.is-required(label="联系人")
            el-select(:disabled="!contactSelect.length", v-model="formData.contact", :placeholder="contactSelect.length ? '请选择联系人' : '请选择供应商'", @change="changeContact")
              el-option(v-for="item in contactSelect", :key="item.value", :label="item.name", :value="item.name")
        el-col(:span="8")
          el-form-item.is-required(label="联系电话")
            el-input(:disabled="true", :value="formData.mobile", placeholder="联系人自动识别")
        el-col(:span="8")
          el-form-item.is-required(label="成本中心")
            el-input(:disabled="pushPlan", v-model="formData.costCenter", placeholder="请输入内容")
      el-row(:gutter="36")
        el-col(:span="8")
          el-form-item.is-required(label="采购日期")
            el-date-picker(v-model="formData.buyTime", type="date", style="width: 100%", placeholder="选择日期", :clearable="false")
        el-col(:span="8")
          el-form-item(label="申请单号")
            el-input(:disabled="pushPlan", @change="changeReqOrder", v-model="formData.reqOrder", placeholder="请输入内容")
        el-col(:span="8")
          el-form-item(label="下联单号")
            el-input(:disabled="true", v-model="formData.downOrder", placeholder="系统自动生成")
      el-row(:gutter="36")
        el-col(:span="24")
          el-form-item.long-item(label="供应商地址", label-width="86px")
            el-input(:disabled="true", v-model="formData.providerAddr", placeholder="选取供应商后自动带出")
      el-row(:gutter="36")
        el-col(:span="24")
          el-form-item(label="备注")
            el-input(v-model="formData.comment", placeholder="请输入内容")
    .ot-tabs
      el-tabs(v-model="activeTabIndex", @tab-click="handlePopTab")
        el-tab-pane(label="基本信息", name="0")
        el-tab-pane(label="付款方式", name="1")
        el-tab-pane(label="订单条款", name="2")
      .ot-init(v-show="showInit", @click="initLine") 初始化行
    .ot-table.tab-base(v-show="tabShows[0]")
      el-table(
        :data="formData.materiels",
        highlight-current-row
        size="mini")
        el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
        el-table-column(align="center", show-overflow-tooltip, prop="incode", label="物料编码")
          template(slot-scope="scope")
            span(v-if="!scope.row.isEdit") {{scope.row.incode}}
            span(v-if="scope.row.isEdit")
              el-button(type="text", @click="showSkuList(scope.$index)", v-text="scope.row.incode ? scope.row.incode : '选择物料'")
        el-table-column(align="center", show-overflow-tooltip, prop="name", label="名称")
          template(slot-scope="scope")
            span {{ scope.row.name }}
        el-table-column(align="center", show-overflow-tooltip, prop="maker", label="制造商")
          template(slot-scope="scope")
            span {{ scope.row.maker | compare-list(skuManSelect) }}
        el-table-column(align="center", show-overflow-tooltip, prop="size", label="规格")
          template(slot-scope="scope")
            span {{ scope.row.size }}
        el-table-column(align="center", show-overflow-tooltip, prop="bom", label="BOM版本")
          template(slot-scope="scope")
            span {{ scope.row.bom }}
        el-table-column(align="center", show-overflow-tooltip, prop="buyUnit", label="采购单位")
          template(slot-scope="scope")
            span {{ scope.row.buyUnit | compare-list(unitSelect) }}
        el-table-column(align="center", show-overflow-tooltip, prop="buyNum", label="采购数量")
          template(slot-scope="scope")
            el-input-number(size="small", :controls="false", v-model="scope.row.buyNum", :min="1", :precision="0", v-show="scope.row.isEdit", style="width: 100%")
            span(v-text="scope.row.buyNum", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="price", label="单价(含税)")
          template(slot-scope="scope")
            el-input-number(size="small", :controls="false", v-model="scope.row.price", :precision="2", :min="0.01", v-show="scope.row.isEdit", style="width: 100%")
            span(v-text="scope.row.price", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="taxRate", label="税率")
          template(slot-scope="scope")
            el-select(v-model="scope.row.taxRate", placeholder="请选择", v-show="scope.row.isEdit")
              el-option(v-for="item in defaultTaxRateSelect", :key="item.value", :label="item.name", :value="item.value")
            span(v-show="!scope.row.isEdit") {{ scope.row.taxRate | compare-list(defaultTaxRateSelect) }}
        el-table-column(align="center", show-overflow-tooltip, prop="countAll", label="价税合计")
          template(slot-scope="scope")
            span {{ ((+scope.row.buyNum) * (+scope.row.price)).toFixed(2) }}
        el-table-column(align="center", show-overflow-tooltip, prop="currency", label="币种")
          template(slot-scope="scope")
            el-select(v-model="scope.row.currency", placeholder="请选择", v-show="scope.row.isEdit")
              el-option(v-for="item in currencySelect", :key="item.value", :label="item.name", :value="item.value")
            span(v-show="!scope.row.isEdit") {{ scope.row.currency | compare-list(currencySelect) }}
        el-table-column(align="center", prop="arrivalTime", label="到货日期", min-width="96px")
          template(slot-scope="scope")
            el-date-picker(v-model="scope.row.arrivalTime", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%")
            span(v-show="!scope.row.isEdit") {{ scope.row.arrivalTime | date-locale }}
        el-table-column(align="center", show-overflow-tooltip, prop="inCount", label="已入库数量")
          template(slot-scope="scope")
            span(v-text="scope.row.inCount")
        el-table-column(align="center", label="操作", width="96px")
          template(slot-scope="scope")
            el-tooltip(content="编辑", v-show="!scope.row.isEdit", @click.native="editOrderMateriel(scope.$index)")
              i.icon-act.el-icon-edit
            el-tooltip(content="添加", v-show="!scope.row.isEdit", @click.native="addOrderMateriel(scope.$index)")
              i.icon-act.el-icon-plus
            el-tooltip(content="删除", v-show="!scope.row.isEdit", @click.native="deleteOrderMateriel(scope.$index)")
              i.icon-act.el-icon-delete
            el-tooltip(content="确定", v-show="scope.row.isEdit", @click.native="insertOrderMateriel(scope.$index)")
              i.icon-act.el-icon-check
            el-tooltip(content="取消", v-show="scope.row.isEdit", @click.native="cancleOrderMateriel(scope.$index)")
              i.icon-act.el-icon-close
    .ot-table.tab-finance(v-show="tabShows[1]")
      el-table(
        :data="formData.finances",
        highlight-current-row
        size="mini")
        el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
        el-table-column(align="center", prop="dueDate", label="应付日期", min-width="96px")
          template(slot-scope="scope")
            el-date-picker(v-model="scope.row.dueDate", v-show="scope.row.isEdit", type="date" ,placeholder="选择日期", style="width: 100%")
            span(v-show="!scope.row.isEdit") {{ scope.row.dueDate | date-locale }}
        el-table-column(align="center", show-overflow-tooltip, prop="dueScale", label="应付比例")
          template(slot-scope="scope")
            el-input-number(size="small", :controls="false", v-model="scope.row.dueScale", :precision="2", :min="0", :max="1", v-show="scope.row.isEdit", style="width: 100%")
            span(v-text="scope.row.dueScale", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="dueMoney", label="应付金额")
          template(slot-scope="scope")
            el-input-number(size="small", :controls="false", v-model="scope.row.dueMoney", :precision="2", :min="0", v-show="scope.row.isEdit", style="width: 100%")
            span(v-text="scope.row.dueMoney", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="payTerm", label="付款条件")
          template(slot-scope="scope")
            el-select(v-model="scope.row.payTerm", placeholder="请选择", v-show="scope.row.isEdit")
              el-option(v-for="item in paymentSelect", :key="item.value", :label="item.name", :value="item.value")
            span(v-show="!scope.row.isEdit") {{ scope.row.payTerm | compare-list(paymentSelect) }}
        el-table-column(align="center", show-overflow-tooltip, prop="prepay", label="是否预付")
          template(slot-scope="scope")
            el-select(v-model="scope.row.prepay", placeholder="请选择", v-show="scope.row.isEdit")
              el-option(v-for="item in prepaySelect", :key="item.value", :label="item.name", :value="item.value")
            span(v-show="!scope.row.isEdit") {{ scope.row.prepay | compare-list(prepaySelect) }}
        el-table-column(align="center", show-overflow-tooltip, prop="checkTerm", label="验收条件")
          template(slot-scope="scope")
            el-input(v-model="scope.row.checkTerm", v-show="scope.row.isEdit")
            span(v-text="scope.row.checkTerm", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="comment", label="备注")
          template(slot-scope="scope")
            el-input(v-model="scope.row.comment", v-show="scope.row.isEdit")
            span(v-text="scope.row.comment", v-show="!scope.row.isEdit")
        el-table-column(align="center", label="操作", width="96px")
          template(slot-scope="scope")
            el-tooltip(content="编辑", v-show="!scope.row.isEdit", @click.native="editOrderFinance(scope.$index)")
              i.icon-act.el-icon-edit
            el-tooltip(content="添加", v-show="!scope.row.isEdit", @click.native="addOrderFinance(scope.$index)")
              i.icon-act.el-icon-plus
            el-tooltip(content="删除", v-show="!scope.row.isEdit", @click.native="deleteOrderFinance(scope.$index)")
              i.icon-act.el-icon-delete
            el-tooltip(content="确定", v-show="scope.row.isEdit", @click.native="insertOrderFinance(scope.$index)")
              i.icon-act.el-icon-check
            el-tooltip(content="取消", v-show="scope.row.isEdit", @click.native="cancleOrderFinance(scope.$index)")
              i.icon-act.el-icon-close
    .ot-table.tab-term(v-show="tabShows[2]")
      el-table(
        :data="formData.terms",
        highlight-current-row
        size="mini")
        el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
        el-table-column(align="center", show-overflow-tooltip, prop="incode", label="编号")
          template(slot-scope="scope")
            el-input(v-model="scope.row.incode", v-show="scope.row.isEdit")
            span(v-text="scope.row.incode", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="termName", label="条款名称")
          template(slot-scope="scope")
            el-input(v-model="scope.row.termName", v-show="scope.row.isEdit")
            span(v-text="scope.row.termName", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="termType", label="条款类型")
          template(slot-scope="scope")
            el-input(v-model="scope.row.termType", v-show="scope.row.isEdit")
            span(v-text="scope.row.termType", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="termContent", label="条款内容")
          template(slot-scope="scope")
            el-input(v-model="scope.row.termContent", v-show="scope.row.isEdit")
            span(v-text="scope.row.termContent", v-show="!scope.row.isEdit")
        el-table-column(align="center", show-overflow-tooltip, prop="comment", label="备注")
          template(slot-scope="scope")
            el-input(v-model="scope.row.comment", v-show="scope.row.isEdit")
            span(v-text="scope.row.comment", v-show="!scope.row.isEdit")
        el-table-column(align="center", label="操作", width="96px")
          template(slot-scope="scope")
            el-tooltip(content="编辑", v-show="!scope.row.isEdit", @click.native="editOrderTerm(scope.$index)")
              i.icon-act.el-icon-edit
            el-tooltip(content="添加", v-show="!scope.row.isEdit", @click.native="addOrderTerm(scope.$index)")
              i.icon-act.el-icon-plus
            el-tooltip(content="删除", v-show="!scope.row.isEdit", @click.native="deleteOrderTerm(scope.$index)")
              i.icon-act.el-icon-delete
            el-tooltip(content="确定", v-show="scope.row.isEdit", @click.native="insertOrderTerm(scope.$index)")
              i.icon-act.el-icon-check
            el-tooltip(content="取消", v-show="scope.row.isEdit", @click.native="cancleOrderTerm(scope.$index)")
              i.icon-act.el-icon-close
    .ot-btns
      el-button.dia-btn(type="primary", plain, @click="close") 取消
      el-button.dia-btn.dia-after(type="primary", @click="saveOrder") 确定
  MaterielList(
    :visible="showMaterielList",
    v-if="showMaterielList",
    :vendor="formData.supply",
    @submit="handleSelect",
    @close="showMaterielList=false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import PurApi from '@/api/purchase';
import MaterielList from '@/components/materiel/materielList';
import validate from '@/utils/validate';
import check from './check';

const { isEmpty } = validate;

export default {
  name: 'orderedit',
  props: {
    title: {
      type: String,
      default: '编辑采购订单'
    },
    visible: Boolean,
    pushPlan: Boolean,
    formData: {
      type: Object,
      default () {
        return {
          materiels: [],
          finances: [],
          terms: [],
          bills: []
        };
      }
    }
  },
  components: {
    MaterielList
  },
  data() {
    return {
      showMaterielList: false,
      finishStatus: false,
      finishContent: '',
      //
      mateBC: [],
      finaBC: [],
      termBC: [],
      billBC: [],
      //
      activeTabIndex: '0',
      tabShows: [true, false, false],
      contactSelect: [],
      prepaySelect: [
        { name: '否', value: 0 },
        { name: '是', value: 1 }
      ]
    };
  },
  methods: {
    close () {
      this.$emit('close');
    },
    handlePopTab () {
      const tabShows = [false, false, false];
      const items = ['materiels', 'finances', 'terms'];
      if (!this.formData[items[this.activeTabIndex]]) {
        this.formData[items[this.activeTabIndex]] = [];
      }
      tabShows[this.activeTabIndex] = true;
      this.tabShows = tabShows;
    },
    changeReqOrder (id) {
      if (id) {
        PurApi.getPlanDetail({ id }).then((result) => {
          if (!result.status) {
            this.formData.applicant = result.obj.applicant;
            this.formData.depart = result.obj.depart;
            this.formData.supply = result.obj.supply;
            this.formData.costCenter = result.obj.costCenter;
            this.formData.materiels = result.obj.materiels;
            this.formData.finances = [];
            this.formData.terms = [];
            this.formData.bills = [];
            if (this.formData.supply) {
              this.getContacts(this.formData.supply);
            }
          }
        });
      }
    },
    getContacts (vendorId, cb) {
      if (vendorId) {
        ComApi.getContacts({ vendorId }).then((result) => {
          this.contactSelect = result.contacts;
          this.addressBC = result.address;
          if (!result.contacts.length) {
            this.formData.contact = '';
            this.formData.mobile = '';
            this.$message.error('此供应商无联系人，请在供应商管理中进行设置');
          } else {
            if (cb) {
              cb();
            }
          }
        }).catch(() => {
          this.contactSelect = [];
          this.formData.providerAddr = '';
        });
      }
    },
    changeSupply (vendorId) {
      this.getContacts(vendorId, () => {
        this.formData.contact = this.contactSelect[0].name;
        this.formData.mobile = this.contactSelect[0].value;
        this.formData.providerAddr = this.addressBC;
      });
    },
    changeContact (name) {
      if (name) {
        let mobile = '';
        for (const contact of this.contactSelect) {
          if (contact.name === name) {
            mobile = contact.value;
          }
        }
        this.formData.mobile = mobile;
      }
    },
    initLine () {
      if (isEmpty(this.formData.supply)) {
        this.$message.info('请先选择供应商');
        return;
      }
      const funcs = ['addOrderMateriel', 'addOrderFinance', 'addOrderTerm', 'addOrderBill'];
      this[funcs[this.activeTabIndex]]();
    },
    saveOrder () {
      const canEmit = check(this.formData);
      if (canEmit) {
        this.$emit('save', this.formData);
      }
    },
    // 显示物料列表
    showSkuList (index) {
      this.skuIndex = index;
      this.showMaterielList = true;
    },
    // 选择物料
    handleSelect(data) {
      if (data) {
        const origin = this.formData.materiels[this.skuIndex];
        const fresh = Object.assign(origin, {
          incode: data.skuId,
          name: data.skuName,
          maker: data.skuBrand,
          size: data.skuSpecification,
          bom: data.bomVersion,
          buyUnit: data.skuUnit
        });
        this.formData.materiels.splice(this.skuIndex, 1, fresh);
        this.showMaterielList = false;
      }
    },
    // 监听物料列表
    addOrderMateriel (index) {
      if (isEmpty(index)) {
        this.formData.materiels.push({
          isEdit: true,
          inCount: 0
        });
      } else {
        this.formData.materiels.splice((index + 1), 0, {
          isEdit: true,
          inCount: 0
        });
      }
    },
    editOrderMateriel (index) {
      this.mateBC[index] = Object.assign({}, this.formData.materiels[index]);
      this.$set(this.formData.materiels[index], 'isEdit', true);
    },
    deleteOrderMateriel (index) {
      this.formData.materiels.splice(index, 1);
      this.mateBC[index] = null;
    },
    insertOrderMateriel (index) {
      this.formData.materiels[index].isEdit = false;
    },
    cancleOrderMateriel (index) {
      if (this.mateBC[index]) {
        this.$set(this.formData.materiels, `${index}`, this.mateBC[index]);
      } else {
        this.deleteOrderMateriel(index);
      }
    },
    // 监听财务列表
    addOrderFinance (index) {
      if (isEmpty(index)) {
        this.formData.finances.push({ isEdit: true });
      } else {
        this.formData.finances.splice((index + 1), 0, { isEdit: true });
      }
    },
    editOrderFinance (index) {
      this.mateBC[index] = Object.assign({}, this.formData.finances[index]);
      this.$set(this.formData.finances[index], 'isEdit', true);
    },
    deleteOrderFinance (index) {
      this.formData.finances.splice(index, 1);
      this.mateBC[index] = null;
    },
    insertOrderFinance (index) {
      this.formData.finances[index].isEdit = false;
    },
    cancleOrderFinance (index) {
      if (this.mateBC[index]) {
        this.$set(this.formData.finances, `${index}`, this.mateBC[index]);
      } else {
        this.deleteOrderMateriel(index);
      }
    },
    // 监听订单列表
    addOrderTerm (index) {
      if (isEmpty(index)) {
        this.formData.terms.push({ isEdit: true });
      } else {
        this.formData.terms.splice((index + 1), 0, { isEdit: true });
      }
    },
    editOrderTerm (index) {
      this.mateBC[index] = Object.assign({}, this.formData.terms[index]);
      this.$set(this.formData.terms[index], 'isEdit', true);
    },
    deleteOrderTerm (index) {
      this.formData.terms.splice(index, 1);
      this.mateBC[index] = null;
    },
    insertOrderTerm (index) {
      this.formData.terms[index].isEdit = false;
    },
    cancleOrderTerm (index) {
      if (this.mateBC[index]) {
        this.$set(this.formData.terms, `${index}`, this.mateBC[index]);
      } else {
        this.deleteOrderTerms(index);
      }
    }
  },
  computed: {
    showInit () {
      const keys = ['materiels', 'finances', 'terms'];
      const current = this.formData[keys[this.activeTabIndex]];
      return !current || !current.length;
    },
    ...mapGetters(['empSelect', 'oneDeptSelect', 'supplySelect', 'skuManSelect', 'currencySelect', 'unitSelect', 'paymentSelect', 'invoiceTypeSelect', 'defaultTaxRateSelect'])
  },
  mounted () {
    const vendorId = this.formData.supply;
    if (vendorId) {
      this.getContacts(vendorId, () => {
        this.formData.contact = this.contactSelect[0].name;
        this.formData.mobile = this.contactSelect[0].value;
        this.formData.providerAddr = this.addressBC;
      });
    }
  }
};
</script>

<style lang="sass">
.cp-order-edit
  .ot-form
    .el-form-item
      width: 100%
      margin-right: 0
    .el-form-item__content
      width: calc(100% - 72px)
    .el-form-item__label
      text-align: left
    .el-select
      width: 100%
    .long-item
      .el-form-item__content
        width: calc(100% - 86px)
  .ot-table
    margin-bottom: 16px
    min-height: 144px
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
    .el-table__empty-block
      display: none
  .ot-tabs
    position: relative
    .ot-init
      position: absolute
      right: 32px
      top: 7px
      color: #409EFF
      font-size: 13px
      font-weight: 500
    .el-tabs__header
      margin-bottom: 2px
  .ot-btns
    margin-top: 24px
    text-align: center
    .dia-btn
      width: 80px
    .dia-after
      margin-left: 40px
</style>
